package com.example.last.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.last.dao.QuestionsDao;
import com.example.last.dao.TypeDao;
import com.example.last.entity.Questions;
import com.example.last.entity.Params;
import com.example.last.entity.Type;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionsService {
    @Resource
    private QuestionsDao questionsDao;
    @Resource
    private TypeDao typeDao; //逻辑层实现多表关联
    public PageInfo<Questions> findBySearch(@Param("Params") Params params) {
        PageHelper.startPage(params.getPageNum(),params.getPageSize());

        List<Questions> list =  questionsDao.findBySearch(params);
        if(CollectionUtil.isEmpty(list)){
            return PageInfo.of(new ArrayList<>());
        }
        for (Questions questions : list){
            if(ObjectUtil.isNotEmpty(questions.getTypeId())){
                Type type = typeDao.selectByPrimaryKey(questions.getTypeId());
                if(ObjectUtil.isNotEmpty(type)){
                    questions.setTypeName(type.getType_name());
                }
            }
        }
        System.out.println("=====================");
        return PageInfo.of(list);
    }

    public void add(Questions questions) {
        questionsDao.add(questions);
    }

    public void update(Questions questions) {
        questionsDao.update(questions);
    }

    public void delete(Integer id) {
        questionsDao.delete(id);
    }

    public List<Questions> findAll() {
        return questionsDao.findAll();
    }
    //自动组卷
    public List<Questions> findByTypeId(@Param("typeId") Integer typeId) {
        return questionsDao.findByTypeId(typeId);
    }

    public List<Questions> findQuestionById(Integer typeId) {
        return questionsDao.findByTypeId(typeId);
    }

    public Questions selectById(Integer index) {
        return questionsDao.selectById(index);
    }
}
